﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HR.ProjectX.BLL.Services.BookingService;
using HR.ProjectX.GUI.ViewModels.Booking;
using HR.ProjectX.BLL.Messaging;

namespace HR.ProjectX.GUI.Controllers
{
    public class BookingController : Controller
    {
        private readonly IBookingService _bookingService;

        public BookingController(IBookingService bookingService)
        {
            _bookingService = bookingService;
        }

        public ActionResult Book(string id)
        {
            BookingBookView bookingView = InitializeBookingBookViewWithIssue(false, "");
            bookingView.VehicleModel = id;

            return View(bookingView);
        }

        [HttpPost]
        public ActionResult Book(BookingBookView bookingView)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    CreateBookingRequest request = new CreateBookingRequest();
                    request.DateFrom = bookingView.DateFrom;
                    request.DateTo = bookingView.DateTo;
                    request.Email = bookingView.Email;
                    request.VehicleModel = bookingView.VehicleModel;

                    _bookingService.CreateBooking(request);

                    TempData["Success"] = "True";

                    return RedirectToAction("ConfirmBooking");
                }
                catch (Exception e)
                {
                    BookingBookView errorView = InitializeBookingBookViewWithIssue(true, e.Message);

                    return View(errorView);
                }
            }

            return View(bookingView);
        }

        public ActionResult ConfirmBooking()
        {
            if (TempData["Success"] != null)
            {
                return View();
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        private BookingBookView InitializeBookingBookViewWithIssue(bool hasIssue, string message)
        {
            BookingBookView bookingView = new BookingBookView();
            bookingView.HasIssue = hasIssue;
            bookingView.Message = message;

            return bookingView;
        }

    }
}
